#!/bin/bash

set -euo pipefail

DEV_PATH=$(dirname "$0")

Error()
{
    echo
    exit 1
}

Include()
{
    INCLUDE_PATH="$DEV_PATH"
    include_name="$1"

    while [[ $include_name =~ \/ ]] 
    do
        INCLUDE_PATH="$INCLUDE_PATH/${include_name%%/*}"
        include_name="${include_name#*/}"
    done

    shift

    # shellcheck disable=SC1090
    . "$INCLUDE_PATH/$include_name" "$@" || Error include $?
}

Include ver

Include env

Include core "$@"

Include utils/i18n "$@"

if [ -z "$*" ] 
then
    echo
    debug_options=( '编译' '测试' )
    inquirer list_input_index "选择操作" debug_options debug_options_index

    if [ "$debug_options_index" -eq 0 ] 
    then
        echo
        inquirer list_input_index "是否部署" ny_options ny_index

        if [ "$ny_index" -eq 0 ] 
        then
            "$DEV_PATH"/make
        else
            "$DEV_PATH"/make install
        fi

        exit 0
    elif [ "$debug_options_index" -eq 1 ] 
    then
        self_options=()
        for file in "$DEV_PATH"/src/*
        do
            if [ ! -d "$file" ] 
            then
                self_options+=("${file##*/}")
            fi
        done

        echo
        inquirer list_input "选择测试的程序" self_options self

        echo
        inquirer text_input "输入参数" args_input "$i18n_blank"

        if [ -z "$args_input" ] 
        then
            args=()
        else
            IFS= read -ra args <<< "$args_input"
        fi
    fi
else
    self=$1
    shift
    args=("${@:-}")
fi

Include src/"$self" "${args[@]:-}"
